package com.anjufang.controller;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class BaseController {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	public BaseController() {
	}

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	protected HttpServletResponse response;

	protected static final String sms_voce = "SMS_VCODE";

	public static final String LIST = "list";
	public static final String VIEW = "view";
	public static final String ADD = "add";
	public static final String SAVE = "save";
	public static final String EDIT = "edit";
	public static final String UPDATE = "update";
	public static final String DELETE = "delete";
	public static final String PAGE = "page";
	public static final String SELECT = "select";

	/**
	 * 获取请求参数中所有的信息
	 * 
	 * @return
	 */
	public Map<String, String> getAllRequestParam() {
		Map<String, String> res = new HashMap<String, String>();
		Enumeration<?> temp = request.getParameterNames();
		if (null != temp) {
			while (temp.hasMoreElements()) {
				String en = (String) temp.nextElement();
				String value = request.getParameter(en);
				// 在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则不保存这个字段>
				if (StringUtils.isNotBlank(value) && !"null".equals(value))
					res.put(en, value);
			}
		}
		return res;
	}

	/**
	 * 获取请求参数中所有的信息--IO流
	 * 
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public Map<String, Object> getAllIOParam() {
		Map<String, Object> res = new HashMap<String, Object>();
		try {
			String req = IOUtils.toString(request.getInputStream());
			for (String param : req.split("&amp;")) {
				String k = param.split("=")[0];
				String v = null;
				if (param.split("=").length > 1) {
					v = param.split("=")[1];
				}
				res.put(k, v);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return res;
	}
	

	/**
	 * 获取用户端请求的参数
	 */
	public String getRequestParam(String key) {
		// 从header中获取token
		String param = request.getHeader(key);
		// 如果header中不存在token，则从参数中获取token
		if (StringUtils.isBlank(param)) {
			param = request.getParameter(key);
		}
		return param;
	}
	
}
